/**
 * Copyright (C) 2009 All Rights Reserved
 * @author sebastian chang
 * @brief practice
 */

#include <sys/time.h>
#include <errno.h>

#include "thread_event.h"

namespace libs {

thread_event_t::thread_event_t()
{
    // Empty
}

thread_event_t::~thread_event_t()
{
    sem_destroy(&_sem);
}

int thread_event_t::initialize(bool state_)
{
    unsigned int value = 0;

    if (state_)
    {
        value = 1;
    }

    return sem_init(&_sem, 0, value) ? errno : 0;
}

int thread_event_t::waitEvent(unsigned long timeout_)
{
    static const unsigned long THOUSAND = 1000;
    static const unsigned long MILLITHOUSAND = 1000000;

    struct timeval tv;
    gettimeofday(&tv, 0);

    struct timespec ts;
    ts.tv_sec = tv.tv_sec;
    ts.tv_nsec = tv.tv_usec * THOUSAND;

    if (0 < timeout_)
    {
        ts.tv_sec += (timeout_ / THOUSAND);
        ts.tv_nsec += (timeout_ % THOUSAND) * MILLITHOUSAND;
    }

    return sem_timedwait(&_sem, &ts) ? errno : 0;
}

int thread_event_t::setEvent()
{
    return sem_post(&_sem) ? errno : 0;
}


} // namespace libs
